package com.dotstone.chipism.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import com.dotstone.chipism.R;
import com.dotstone.chipism.adapter.SceneAdapter;
import com.dotstone.chipism.bean.Device;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.bean.Scene;
import com.dotstone.chipism.bean.Scene_Task;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.listener.UpdateDataListener;
import com.dotstone.chipism.ui.login.LoginActivity;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.NetUtil;
import com.dotstone.chipism.util.SPUtils;
import com.dotstone.chipism.util.SocketManager;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.util.Util;
import com.dotstone.chipism.view.BaseAnimatorSet;
import com.dotstone.chipism.view.BlurBehind;
import com.dotstone.chipism.view.NormalDialog;
import com.dotstone.chipism.view.OnBlurCompleteListener;
import com.dotstone.chipism.view.OnBtnClickL;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class SceneListActivity extends BaseActivity {
	private TextView tv_statusBar_mian;
	private LinearLayout mBackL;
	private Button mBackB;
	private ListView mSceneLv;
	private Button mAddSceneB;
	private static final int GET_SCENE_SUCCESS = 0;
	private List<Scene> mScenes = new ArrayList<Scene>();
	private SceneAdapter mAdapter;
	private BaseAnimatorSet bas_in;
	private BaseAnimatorSet bas_out;
	private NormalDialog mNormalDialog;
	private SVProgressHUD mSvprogressbar;


	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_btn:
			finish();
			break;
		case R.id.add_btn:
			BlurBehind.getInstance().execute(MainActivity.mainActivity, new OnBlurCompleteListener() {
				@Override
				public void onBlurComplete() {
					Intent intent = new Intent(getApplicationContext(), SceneEditActivity.class);
					intent.putExtra("position", -1);
					intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
					startActivity(intent);
					finish();
				}
			});
			break;

		default:
			break;
		}
	}

	@SuppressLint("HandlerLeak")
	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case GET_SCENE_SUCCESS:
				getAllTasks();
				break;
			case 1:
				mHandler.postDelayed(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						if (mSvprogressbar.isShowing()) {
							mSvprogressbar.dismiss();
						}
						mScenes = DeviceManager.getInstance().getScenes();
						Log.i("wmy", getLocalClassName() + "mScenes.size = " + mScenes.size());
						if (mAdapter == null) {
							mAdapter = new SceneAdapter(getApplicationContext(), mScenes);
							mSceneLv.setAdapter(mAdapter);
						} else {
							mAdapter.notifyDataSetChanged();
						}
					}
				}, 1000);

				break;
			default:
				break;
			}
		}
	};

	private void getAllTasks() {
		mScenes = DeviceManager.getInstance().getScenes();
		if (mScenes.size() > 0) {
			for (int i = 0; i < mScenes.size(); i++) {
				getTaskBySceneId(i, mScenes.get(i).getSceneId());
			}
		} else {
			ToastShow.Show(getApplicationContext(), "没有场景");
			Message msg = Message.obtain();
			msg.what = 1;
			mHandler.sendMessage(msg);
		}
	}

	private void getTaskBySceneId(final int pos, final String sceneId) {
		if (NetUtil.isNetworkAvailable(getApplicationContext())) {
			if (!Util.isLogin(getApplicationContext())) {
				return;
			}
			RequestParams params = new RequestParams(HttpURL.GET_SCENE_TASK_URL);
			params.setAsJsonContent(true);
			JSONObject obj=null;
			try {
				obj = new JSONObject();
				obj.put("key", "10000");
				obj.put("id", sceneId);
				obj.put("requestTime", "" + System.currentTimeMillis());
				obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());
			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					Log.e("wmy", "get scene task =" + sceneId + " " + result);
					try {
						JSONObject jsonObject = new JSONObject(result);
						String resultCode = jsonObject.getString("resultCode");
						if (resultCode.equals("1")) {
							JSONArray data = jsonObject.getJSONArray("data");
							DeviceManager.getInstance().getSceneById(sceneId).clearTask();
							if (data.length() != 0) {
								// DeviceManager.getInstance().clearTask();
								List<Device> childDevices = new ArrayList<Device>();
								List<Scene_Task> tasks = new ArrayList<Scene_Task>();
								String sId = null;
								for (int i = 0; i < data.length(); i++) {
									JSONObject jo = data.getJSONObject(i);
									String stId = jo.getString("stId");
									String cmd = jo.getString("cmd");
									String cmdName = jo.getString("cmdName");
								//	String cmdName=cmdName1.split("\\|")[0];
								//	String deviceName=cmdName1.split("\\|")[1];
									String did = jo.getString("did");
									Device device = DeviceManager.getInstance().getDeviceById(did);
									boolean e = false;
									for (Device d : childDevices) {
										if (d.getDeviceID().equals(device.getDeviceID())) {
											e = true;
										}
									}
									if (!e) {
										childDevices.add(device);
									}
									sId = jo.getString("sceneId");
									int delayed = jo.getInt("delayed");
									int hour = delayed / 3600;
									int min = delayed / 60;
									int sec = delayed % 60;
									Scene_Task task = new Scene_Task(stId, delayed, did, cmd, sId, cmdName, hour, min,
											sec, device.getMainDeviceId());
									tasks.add(task);
									DeviceManager.getInstance().addTask(task);
									Log.e("wmy", "1317 tasks.size() = " + tasks.size());
								}
								DeviceManager.getInstance().getSceneById(sceneId).setDevices(childDevices);
								DeviceManager.getInstance().getSceneById(sceneId).setScene_Tasks(tasks);
								DeviceManager.getInstance().setSceneChildDevices(sceneId, childDevices);
								DeviceManager.getInstance().getScenes().get(pos).setDevices(childDevices);
								// sceneChildDevicesMap.put(sceneId,
								// childDevices);
							}
							Message msg = Message.obtain();
							msg.what = 1;
							mHandler.sendMessage(msg);
							if (pos == mScenes.size() - 1) {
								DeviceManager.getInstance().setNeedToRefreshScenes(false);
							}
						} else if (resultCode.equals("10003")) {
							// 在这里判断token有效性
							Toast.makeText(getApplicationContext(), "您的登陆已超时，请重新登陆", Toast.LENGTH_SHORT).show();
							startActivity(new Intent(getApplicationContext(), LoginActivity.class));
							finish();
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onCancelled(CancelledException arg0) {

				}

				@Override
				public void onError(Throwable arg0, boolean arg1) {
					// lt.error();
				}

				@Override
				public void onFinished() {

				}
			});
		}

	}

	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub

	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_scene_list;
	}

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		BlurBehind.getInstance()
				// .withAlpha(80)
				// .withFilterColor(Color.parseColor("#000000"))
				.setBackground(this);

		tv_statusBar_mian = $(R.id.tv_statusBar_mian);
		boolVersion();
		mBackL = $(R.id.back_layout);
		mBackL.setVisibility(View.GONE);
		mBackB = $(R.id.back_btn);
		mBackB.setVisibility(View.VISIBLE);
		mSceneLv = $(R.id.scene_lv);
		mAddSceneB = $(R.id.add_btn);
		mSvprogressbar = new SVProgressHUD(SceneListActivity.this);
		mBackB.setOnClickListener(this);
		mAddSceneB.setOnClickListener(this);
		mSceneLv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, final int position, long arg3) {
				// TODO Auto-generated method stub
				BlurBehind.getInstance().execute(MainActivity.mainActivity, new OnBlurCompleteListener() {
					@Override
					public void onBlurComplete() {
						Intent intent = new Intent(SceneListActivity.this, SceneEditActivity.class);
						intent.putExtra("position", position);
						intent.putExtra("sceneId", mScenes.get(position).getSceneId());
						intent.putExtra("sceneName", mScenes.get(position).getSceneName());
						intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
						startActivity(intent);
						// finish();
					}
				});
			}
		});
		mSceneLv.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View v, final int p, long arg3) {
				// TODO Auto-generated method stub

				mNormalDialog = new NormalDialog(SceneListActivity.this);
				mNormalDialog.content("是否删除该情景：" + mScenes.get(p).getSceneName() + "？").style(NormalDialog.STYLE_TWO)//
						.titleTextSize(18)//
						.showAnim(bas_in)//
						.dismissAnim(bas_out)//
						.show();
				mNormalDialog.setOnBtnClickL(new OnBtnClickL() {
					@Override
					public void onBtnClick() {
						mNormalDialog.dismiss();
					}
				}, new OnBtnClickL() {
					@Override
					public void onBtnClick() {
						mNormalDialog.dismiss();
						deleteScene(mScenes.get(p).getSceneId());
					}
				});
				return true;
			}
		});
	//	deleteScene("38");

	}

	private void deleteScene(String id) {

		if (!NetUtil.isNetworkAvailable(getApplicationContext())) {
			ToastShow.Show(getApplicationContext(), "没有网络");
			return;
		}
		mSvprogressbar.showWithStatus("正在删除");
		RequestParams params = new RequestParams(HttpURL.DELETE_SCENE_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("sceneId", id);
			obj.put("key", "10000");
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("test", "delete scene=" + result);
				// deleteLocal();
				try {
					JSONObject jsonObject = new JSONObject(result);
					String resultCode = jsonObject.getString("resultCode");
					if (resultCode.equals("1")) {
						ToastShow.Show(getApplicationContext(), "删除成功");
						getAllScene();
					} else {
						throw new Exception();
					}
				} catch (Exception e) {
					e.printStackTrace();
					ToastShow.Show(getApplicationContext(), "删除失败，请稍后再试");
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {

			}

			@Override
			public void onFinished() {

			}
		});
	}

	private void getAllScene() {
		if (NetUtil.isNetworkAvailable(getApplicationContext())) {
			if (!Util.isLogin(getApplicationContext())) {
				return;
			}
			RequestParams params = new RequestParams(HttpURL.GET_SCENE_LIST);
			params.setAsJsonContent(true);
			JSONObject obj =null;
			try {
				obj = new JSONObject();
				obj.put("key", "10000");
				obj.put("hid", DeviceManager.getInstance().hid);
				obj.put("requestTime", "" + System.currentTimeMillis());
				obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
				Log.d("test", " get all scene = " + obj.toString());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());
			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					Log.e("wmy", "get all scene=" + result);
					try {
						JSONObject jsonObject = new JSONObject(result);
						String resultCode = jsonObject.getString("resultCode");
						if (resultCode.equals("1")) {
							DeviceManager.getInstance().clearScene();
							JSONObject data = jsonObject.getJSONObject("data");
							JSONArray ja = data.getJSONArray("lscene");
							Log.e("wmy", "length " + ja.length());
							if (data.length() != 0) {
								for (int i = 0; i < ja.length(); i++) {
									String sceneId = ja.getJSONObject(i).getString("sceneId");
									String userId = ja.getJSONObject(i).getString("userId");
									String sceneName = ja.getJSONObject(i).getString("sceneName");
									long createTime = ja.getJSONObject(i).getLong("createTime");
									int status = ja.getJSONObject(i).getInt("status");
									String hid = ja.getJSONObject(i).getString("hid");
									Scene scene = new Scene(sceneId, userId, sceneName, status, hid);
									DeviceManager.getInstance().addScene(scene);
								}
							}
							Message msg = Message.obtain();
							msg.what = GET_SCENE_SUCCESS;
							mHandler.sendMessage(msg);

						} else if (resultCode.equals("10003")) {
							// 在这里判断token有效性
							ToastShow.Show(getApplicationContext(), "您的登陆已超时，请重新登陆");
							startActivity(new Intent(getApplicationContext(), LoginActivity.class));
							finish();
						} else {
							if (mSvprogressbar.isShowing()) {
								mSvprogressbar.dismiss();
							}
							String errorMsg = jsonObject.optString("errorMsg");
							ToastShow.Show(getApplicationContext(), "获取情景失败：" + errorMsg);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onCancelled(CancelledException arg0) {
				}

				@Override
				public void onError(Throwable arg0, boolean arg1) {
					// lt.error();
				}

				@Override
				public void onFinished() {
				}
			});
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		initData();
		SocketManager.getInstance().setOnUpdateDataListener(new UpdateDataListener() {

			@Override
			public void onUpdate() {
				// TODO Auto-generated method stub
				getAllScene();
			}
		});
	}

	private void initData() {
		// TODO Auto-generated method stub
		// 获取场景
		if (DeviceManager.getInstance().isNeedToRefreshScenes()) {
			mSvprogressbar.showWithStatus("正在获取场景");
			getAllScene();
		} else {
			mScenes = DeviceManager.getInstance().getScenes();
			Log.i("wmy", getLocalClassName() + "mScenes.size = " + mScenes.size());
			mAdapter = new SceneAdapter(getApplicationContext(), mScenes);
			mSceneLv.setAdapter(mAdapter);
		}
	}

	@Override
	public void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}

	public void boolVersion() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			Window window = getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			// getWindow().addFlags(
			// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			// 改变titlebar的高度
			int statusbarHeight = BarUtils.getStatusBarHeight(this);
			RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) tv_statusBar_mian
					.getLayoutParams();
			layoutParams1.height = statusbarHeight;
			tv_statusBar_mian.setLayoutParams(layoutParams1);
			tv_statusBar_mian.setVisibility(View.VISIBLE);

		} else {
			tv_statusBar_mian.setVisibility(View.GONE);
		}
	}



}
